import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)    # 通道12为PWM输出IO
GPIO.setup(11, GPIO.OUT)    # 11号引脚为IN1,控制电机转向
GPIO.setup(10, GPIO.OUT)    # 10号引脚为IN2,控制电机转向

p = GPIO.PWM(12, 1000)  # 频率为 1KHz
p.start(0)
try:
    while 1:
        for dc in range(100, 1001, 50):
            GPIO.output(11, GPIO.HIGH)
            GPIO.output(10, GPIO.LOW)  # 电机正转
            p.ChangeDutyCycle(dc)
            time.sleep(0.5)

        time.sleep(2)                   # 延时2秒

        for dc in range(1000, 99, -5):
            GPIO.output(11, GPIO.LOW)
            GPIO.output(10, GPIO.HIGH)  # 电机反转
            p.ChangeDutyCycle(dc)
            time.sleep(0.5)

        time.sleep(2)                   # 延时2秒
except KeyboardInterrupt:
    pass
p.stop()
GPIO.cleanup()